package com.tim.app.ui.activity;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.application.library.net.StringResponseCallback;
import com.application.library.runtime.event.EventManager;
import com.application.library.util.StringUtil;
import com.application.library.util.TimeUtil;
import com.lzy.okhttputils.OkHttpUtils;
import com.tim.app.MyTextWatch.MyTextWatcher;
import com.tim.app.R;
import com.tim.app.RT;
import com.tim.app.constant.EventTag;
import com.tim.app.manager.ImagePickerManager;
import com.tim.app.server.api.API_User;
import com.tim.app.server.logic.UserManager;
import com.tim.app.server.result.ResponseResult;
import com.tim.app.util.SoftKeyboardUtil;
import com.tim.app.util.ToastUtil;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 修改用户信息页面
 */
public class ModtifyUserInfoActivity extends BaseActivity {

    private static final String TAG = "ModtifyUserInfoActivity";
    private ImageButton ibBack;
    private EditText etNickname, etSignature;
    private TextView tvAge;
    private String nickname, intro;
    private String currentName = "";
    private String currentDes = "";

    private String initUserName = "";
    private int indexName;
    private int indexDes;
    private String birthday = "";
    private String constellation = "";
    private final int MAX_NAME = 8;
    private final int MAX_NAME_BYTE = 2 * MAX_NAME;
    private final int MAX_DES = 30;
    private final int MAX_DES_BYTE = 2 * MAX_DES;

    private final int MIN_NAME = 2;
    private final int MIN_NAME_BYTE = 2 * MIN_NAME;

    int currentYear;
    int currentMonth;
    int currentDay;

    ImagePickerManager imagePicker;
    DatePickerDialog datePickerDialog;
    DatePicker picker;

    public static void start(Context context) {
        Intent intent = new Intent(context, ModtifyUserInfoActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_modtify_info_detail;
    }

    @Override
    public void initView() {
        ibBack = (ImageButton) findViewById(R.id.ibBack);
        etNickname = (EditText) findViewById(R.id.etNickname);
        tvAge = (TextView) findViewById(R.id.tvAge);
        etSignature = (EditText) findViewById(R.id.etSignature);

        findViewById(R.id.tvSave).setOnClickListener(this);
        ibBack.setOnClickListener(this);
        tvAge.setOnClickListener(this);
        initTextWatchListener();
    }

    @Override
    public void initData() {
        if (!TextUtils.isEmpty(UserManager.ins().getLoginUser().getName())) {
            initUserName = UserManager.ins().getLoginUser().getName();
            String nameSub = StringUtil.getSubStringByCNlength(UserManager.ins().getLoginUser().getName(), MAX_NAME);
            if (StringUtil.getTotalBytes(UserManager.ins().getLoginUser().getName()) > MAX_NAME_BYTE) {
                etNickname.setText(nameSub);
                etNickname.setSelection(nameSub.length());
            } else {
                etNickname.setText(UserManager.ins().getLoginUser().getName());
                etNickname.setSelection(UserManager.ins().getLoginUser().getName().length());
            }
        }
        if (!TextUtils.isEmpty(UserManager.ins().getLoginUser().getIntroduce())) {
            etSignature.setText(UserManager.ins().getLoginUser().getIntroduce());
        }else{
            etSignature.setHint(getString(R.string.signatureHint));
        }

        if (!TextUtils.isEmpty(UserManager.ins().getLoginUser().getBirthday())) {
            long time = Long.valueOf(UserManager.ins().getLoginUser().getBirthday());
            birthday = TimeUtil.formatDate(this, time);
        }
        tvAge.setText(UserManager.ins().getLoginUser().getAge() + "岁  " + UserManager.ins().getLoginUser().getConstellation());

        imagePicker = ImagePickerManager.ins();
        imagePicker.setMultiMode(false);
        imagePicker.setCrop(false);
        if (android.os.Build.MODEL.contains("HM NOTE")) {
            imagePicker.setShowCamera(false);
        }

        Calendar calendar = Calendar.getInstance();
        currentYear = calendar.get(Calendar.YEAR) - 27;
        currentMonth = calendar.get(Calendar.MONTH);
        currentDay = calendar.get(Calendar.DAY_OF_MONTH);

        try {
            SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
            Date beginDate = new Date();
            Calendar date = Calendar.getInstance();
            date.setTime(beginDate);
            date.set(Calendar.YEAR, date.get(Calendar.YEAR) - 12);
            Date endDate = dft.parse(dft.format(date.getTime()));

            date.set(Calendar.YEAR, date.get(Calendar.YEAR) - 80);
            Date startDate = dft.parse(dft.format(date.getTime()));

            datePickerDialog = new DatePickerDialog(ModtifyUserInfoActivity.this, AlertDialog.THEME_HOLO_LIGHT, Datelistener, currentYear, currentMonth, currentDay);
            picker = datePickerDialog.getDatePicker();
            picker.setMaxDate(endDate.getTime());
            picker.setMinDate(startDate.getTime());
            datePickerDialog.updateDate(currentYear, currentMonth, currentDay);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        SoftKeyboardUtil.hideSoftKeyboard(etNickname);
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(TAG);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibBack:
                onBackPressed();
                break;
            case R.id.tvAge:
                datePickerDialog.show();//显示DatePickerDialog组件
                break;
            case R.id.tvSave:
                updateUserInfo();
                break;
        }
    }

    private void initTextWatchListener() {
        etNickname.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (StringUtil.getTotalBytes(etNickname.getText().toString().trim()) <= MAX_NAME_BYTE) {
                    currentName = etNickname.getText().toString().trim();
                }
                if (!StringUtil.checkEmojText(etNickname.getText().toString().trim())) {
                    indexName = etNickname.getSelectionStart();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String nameChange = etNickname.getText().toString().trim();
                if (nameChange.contains("...")) {
                    return;
                }
                if (StringUtil.checkEmojText(nameChange)) {
                    ToastUtil.showToast("昵称不能包含特殊字符，只支持中英文、数字及下划线");
                    etNickname.setText(StringUtil.replaceEmojText(nameChange));
                    etNickname.setSelection(indexName);
                    return;
                }
                if (StringUtil.getTotalBytes(nickname) > MAX_NAME_BYTE) {
                    nickname = etNickname.getText().toString().trim();
                    if (StringUtil.getTotalBytes(nickname) > MAX_NAME_BYTE) {
                        etNickname.setError(getString(R.string.txt_info_name));
                    }
                } else {
                    nickname = etNickname.getText().toString().trim();
                    if (StringUtil.getTotalBytes(nickname) > MAX_NAME_BYTE) {
                        etNickname.setText(currentName);
                        etNickname.setSelection(currentName.length());
                        ToastUtil.showToast(RT.getString(R.string.txt_info_name));
                    }
                }
            }
        });
        etSignature.addTextChangedListener(new MyTextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                if (StringUtil.getTotalBytes(etSignature.getText().toString().trim()) <= MAX_DES_BYTE) {
                    currentDes = etSignature.getText().toString().trim();
                }
                if (!StringUtil.checkEmojText(etSignature.getText().toString().trim())) {
                    indexDes = etSignature.getSelectionStart();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                String dexChange = etSignature.getText().toString().trim();
                if (dexChange.contains("...")) {
                    return;
                }
                if (StringUtil.checkEmojText(dexChange)) {
                    ToastUtil.showToast(RT.getString(R.string.disable_emoji));
                    etSignature.setText(StringUtil.replaceEmojText(dexChange));
                    etSignature.setSelection(indexDes);
                    return;
                }
                if (StringUtil.getTotalBytes(intro) > MAX_DES_BYTE) {
                    intro = etSignature.getText().toString().trim();
                    if (StringUtil.getTotalBytes(intro) > MAX_DES_BYTE) {
                        etSignature.setError(getString(R.string.txt_info_self));
                    }
                } else {
                    intro = etSignature.getText().toString().trim();
                    if (StringUtil.getTotalBytes(intro) > MAX_DES_BYTE) {
                        etSignature.setText(currentDes);
                        etSignature.setSelection(currentDes.length());
                        ToastUtil.showToast(RT.getString(R.string.txt_info_self));
                    }
                }
            }
        });
    }


    private void updateUserInfo() {
        nickname = etNickname.getText().toString().trim();
        intro = etSignature.getText().toString().trim();
        if(!StringUtil.checkUserName(nickname)){
            ToastUtil.showToast("昵称不能包含特殊字符，只支持中英文、数字及下划线");
            return;
        }
        String name = "";
        if (!initUserName.equals(nickname)) {
            name = nickname;
        }
        if (TextUtils.isEmpty(nickname)) {
            ToastUtil.showToast(RT.getString(R.string.txt_name_nonull));
            return;
        }
        if (StringUtil.getTotalBytes(nickname) < MIN_NAME_BYTE ) {
            ToastUtil.showToast(RT.getString(R.string.txt_info_name));
            return;
        }
        if (StringUtil.getTotalBytes(nickname) > MAX_NAME_BYTE) {
            ToastUtil.showToast(RT.getString(R.string.txt_info_name));
            return;
        }
        showLoadingDialog();
        final int age = getAge();
        if (!TextUtils.isEmpty(birthday)) {
            constellation = TimeUtil.getConstellation(ModtifyUserInfoActivity.this, birthday, "yyyy-MM-dd");
        }

        API_User.ins().modtifyUserInfo(TAG, name, age, constellation, intro, birthday, "", "", "", "", new StringResponseCallback() {
            @Override
            public boolean onStringResponse(String resultValue, int errCode, String errMsg, int id, boolean fromCache) {
                hideLoadingDialog();
                if (errCode == ResponseResult.ResultStatus.OK) {
                    UserManager.ins().getLoginUser().setAge(age);
                    if (!TextUtils.isEmpty(nickname)) {
                        UserManager.ins().getLoginUser().setName(nickname);
                    }
                    if (!TextUtils.isEmpty(intro)) {
                        UserManager.ins().getLoginUser().setIntroduce(intro);
                    } else {
                        UserManager.ins().getLoginUser().setIntroduce("");
                    }
                    if (!TextUtils.isEmpty(constellation)) {
                        UserManager.ins().getLoginUser().setConstellation(constellation);
                    }
                    if (age > 0) {
                        UserManager.ins().getLoginUser().setAge(age);
                    }
                    if (!TextUtils.isEmpty(birthday)) {
                        UserManager.ins().getLoginUser().setConstellation(birthday);
                    }
                    UserManager.ins().saveUserInfo(UserManager.ins().getLoginUser());
                    EventManager.ins().sendEvent(EventTag.ACCOUNT_UPDATE_INFO, 0, 0, null);
                    ToastUtil.showToast(RT.getString(R.string.txt_save_success));
                    finish();
                } else {
                    ToastUtil.showToast(errMsg);
                }
                return false;
            }
        });
    }


    private DatePickerDialog.OnDateSetListener Datelistener = new DatePickerDialog.OnDateSetListener() {
        /**params：view：该事件关联的组件
         * params：myyear：当前选择的年
         * params：monthOfYear：当前选择的月
         * params：dayOfMonth：当前选择的日
         */
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {

            //修改year、month、day的变量值，以便以后单击按钮时，DatePickerDialog上显示上一次修改后的值
            //更新日期
            updateDate(year, monthOfYear, dayOfMonth);

        }

        //当DatePickerDialog关闭时，更新日期显示
        private void updateDate(int year, int monthOfYear, int dayOfMonth) {
            //在TextView上显示日期
            currentYear = year;
            currentMonth = monthOfYear + 1;
            currentDay = dayOfMonth;

            birthday = currentYear + "-" + currentMonth + "-" + currentDay;
            tvAge.setText(getAge() + "岁  " + TimeUtil.getConstellation(ModtifyUserInfoActivity.this, birthday, "yyyy-MM-dd"));
        }
    };

    private int getAge() {
        Calendar calendar = Calendar.getInstance();
        return calendar.get(Calendar.YEAR) - currentYear;
    }

}
